package top.v5it.japi.ddd.example.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.v5it.japi.ddd.core.repository.Repository;
import top.v5it.japi.ddd.core.service.impl.BasicServiceImpl;
import top.v5it.japi.ddd.example.domain.event.OrderDTO;
import top.v5it.japi.ddd.example.domain.proxy.ProductVO;
import top.v5it.japi.ddd.example.order.entity.Order;
import top.v5it.japi.ddd.example.order.entity.OrderDetail;
import top.v5it.japi.ddd.example.order.event.OrderEvent;
import top.v5it.japi.ddd.example.order.proxy.ProductService;
import top.v5it.japi.ddd.example.order.service.OrderService;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhanpu
 * @date 2023/10/26
 */
@Service(OrderService.SERVICE_NAME)
@RequiredArgsConstructor
public class OrderServiceImpl extends BasicServiceImpl<Repository> implements OrderService {

    private final RestTemplate restTemplate;
    private final Snowflake snowflake;
    private final ProductService productService;

    @Override
    public void add(Order entity) {
        Assert.notNull(entity, "请求参数[entity]不能为空");
        final Object result = restTemplate.getForObject("http://example-member/orm/member/search_by_id?id=" + entity.getMember_id(), Object.class);
        Assert.notNull(result, "请求参数[order.member_id = {}]非法", entity.getMember_id());
        // 设置id
        Optional.of(entity).filter(t -> Objects.isNull(t.getId())).ifPresent(t -> t.setId(snowflake.nextId()));
        // 设置外键
        Optional.of(entity).map(Order::getOrder_details).filter(CollUtil::isNotEmpty).ifPresent(t -> {
            t.replaceAll(order -> {
                order.setId(snowflake.nextId());
                order.setOrder_id(entity.getId());
                return order;
            });
        });
        basicDao.insert(entity);

        // 转换数据
        final OrderDTO orderDTO = new OrderDTO();
        orderDTO.setMember_id(entity.getMember_id());
        orderDTO.setTotal_amount(entity.getTotal_amount());
        orderDTO.setType(OrderEvent.EventType.create.getType());
        // 创建事件
        final OrderEvent event = new OrderEvent(orderDTO, OrderEvent.EventType.create);
        SpringUtil.publishEvent(event);
    }

    @Override
    public Order searchById(Long id) {
        Assert.notNull(id, "请求id不能为空");
        final Order order = basicDao.load(id, new Order());
        final List<OrderDetail> order_details = order.getOrder_details();
        final List<Long> collect = order_details.stream().map(OrderDetail::getProduct_id).collect(Collectors.toList());
        final List<ProductVO> products = productService.getProducts(MapUtil.of("ids", collect));
        final Map<Long, List<ProductVO>> listMap = products.stream().collect(Collectors.groupingBy(ProductVO::getId));
        order_details.replaceAll(t -> {
            t.setProduct(listMap.get(t.getProduct_id()).get(0));
            return t;
        });
        order_details.replaceAll(t -> {
            t.setOrder_id(null);
            t.setProduct_id(null);
            return t;
        });
        return order;
    }

}
